package com.example.config;

import com.example.model.User;
import com.example.model.UserRole;
import com.example.service.UserService;
import com.example.util.JwtUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class RoleAuthorizationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private UserService userService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前用户ID
        Long userId = (Long) request.getAttribute("userId");
        if (userId == null) {
            // 如果请求中没有用户ID，说明JWT拦截器未通过或没有配置
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "未授权");
            return false;
        }

        // 获取用户信息
        User user = userService.getUserById(userId);
        if (user == null) {
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在");
            return false;
        }

        // 验证是否是管理员
        if (!UserRole.ROLE_ADMIN.name().equals(user.getRole())) {
            sendErrorResponse(response, HttpServletResponse.SC_FORBIDDEN, "需要管理员权限");
            return false;
        }

        return true;
    }

    private void sendErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
        Map<String, String> error = new HashMap<>();
        error.put("message", message);
        
        response.setStatus(status);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(error));
    }
} 